import {
  getTokenMsgArr
} from '@/config/apiServe/fetch-config.js';
import {
  tokenHolder
} from '@/config/apiServe/new-rpc.js'
export default {
  computed: {
    baseCoin() {
      return this.$store.state.baseCoinIcon
    }
  },
  created() {
    this.getTokens()
  },
  methods: {
    async getTokens() {
      let tokens = []
      let symbols = []
      let matchs = []
      await this.Rpc.queryAllTokens().then((data) => {
        if (!data.result) return
        tokens = data.result.tokens
        symbols = tokens.map(item => {
          return item.symbol
        })
      })
      await getTokenMsgArr(symbols,process.env.VUE_APP_PLATFORM||'').then(res => {
        if (res.code === 0) {
          res.data.forEach((item, index) => {
            tokens[index] = {
              ...item,
              ...tokens[index]
            }
          })
        } else return
      })
      tokens = tokens.reverse()
      tokens = tokens.sort(this.compare('createdTime', false))
      tokens.map((item, index) => {
        item.value = item.symbol
        item.icon = item.icon || this.baseCoin
        item.index = index + 1
        // item.introduce = (item.introduce && JSON.parse(item.introduce)['zh-CN'] !== "") ? JSON.parse(item.introduce)['zh-CN'] : item.introduction
        // item.nickname = (item.nickname && JSON.parse(item.nickname)['zh-CN'] !== "") ? JSON.parse(item.nickname)['zh-CN'] : ''
        matchs.push({
          match: [{
            value: item.symbol,
            key: 'asset_symbol'
          }],
          range: [{
            key: 'balance',
            gt: 0
          }]
        })
      })
      await tokenHolder([matchs]).then(res => {
        if (res.error === null) {
          res.result.forEach((item, index) => {
            tokens[index].holders = item
          })
        }
      })
      this.$store.commit('updateTokenList', tokens)
    },
    compare(attr, rev) {
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = (rev) ? 1 : -1;
      }
      return function (a, b) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      }
    },
  }
}